package de.fhwgt.quiz.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.fhwgt.quiz.application.Player;
import de.fhwgt.quiz.application.Quiz;
import de.fhwgt.quiz.error.QuizError;
import de.fhwgt.quiz.loader.LoaderException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * Servlet implementation class WebQuiz
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Quiz quiz;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        quiz = Quiz.getInstance();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 * @see doPost
	 * macht das selbe wie doPost 
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        QuizError error = new QuizError();
		if (request.getParameter("user")!=null){
	        String user = request.getParameter("user");
	        Player player = this.quiz.createPlayer(user, error);
			if(player!=null){
				try {
					DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
					DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
					// root elements
					Document doc = docBuilder.newDocument();
					Element rootElement = doc.createElement("loginResponse");
					doc.appendChild(rootElement);	
					rootElement.setAttribute("id", "0");											//0 wenn login erfolgreich
					// write the content into xml file
					if(player.isSuperuser()){
						System.out.println(":::LoginServlet::"+player.getName()+"is superuser");
						Element firstname = doc.createElement("playerID");
						firstname.appendChild(doc.createTextNode(player.getId().toString()));
						rootElement.appendChild(firstname);	
					}
					else{
						System.out.println(":::LoginServlet::"+player.getName()+"is not superuser");
						Element firstname = doc.createElement("playerID");
						firstname.appendChild(doc.createTextNode(player.getId().toString()));
						rootElement.appendChild(firstname);	
					}

					TransformerFactory transformerFactory = TransformerFactory.newInstance();
					Transformer transformer = transformerFactory.newTransformer();					
					DOMSource source = new DOMSource(doc);
					StreamResult result = new StreamResult(response.getWriter());
					transformer.transform(source, result);
					
					
				  } catch (ParserConfigurationException pce) {
					pce.printStackTrace();
				  } catch (TransformerException tfe) {
					tfe.printStackTrace();
				  }
			}else{
				if(error.isSet()){
					try {
						//quiz.signalPlayerChange();
						DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
						DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
						// root elements
						Document doc = docBuilder.newDocument();
						Element rootElement = doc.createElement("loginResponse");
						doc.appendChild(rootElement);	
						rootElement.setAttribute("id", "1");
						// firstname elements
						Element firstname = doc.createElement("ErrorDescription");
						firstname.appendChild(doc.createTextNode(error.getDescription()));
						rootElement.appendChild(firstname);				 
						// lastname elements
						Element lastname = doc.createElement("ErrorCode");
						lastname.appendChild(doc.createTextNode(Integer.toString(error.getStatus())));
						rootElement.appendChild(lastname);
						// write the content into xml file
						TransformerFactory transformerFactory = TransformerFactory.newInstance();
						Transformer transformer = transformerFactory.newTransformer();					
						DOMSource source = new DOMSource(doc);
						StreamResult result = new StreamResult(response.getWriter());
						transformer.transform(source, result);
					  } catch (ParserConfigurationException pce) {
						pce.printStackTrace();
					  } catch (TransformerException tfe) {
						tfe.printStackTrace();
					  }
				}
			}
	    }	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 * Username wird über einen HTTP-Post request übergeben.
	 * Wenn erfolgreich return -> 0
	 * Wenn Fehlgeschlagen -> 1 + errordcode + errormessage
	 */

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
